package top.boycharse.blog.secruity.filter;

import com.sun.org.apache.xerces.internal.xs.StringList;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;
import top.boycharse.blog.secruity.SecruityConstant;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class JwtAuthorizationFilter extends BasicAuthenticationFilter {

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        UsernamePasswordAuthenticationToken authenticationToken = getAuthentication(request);
        if (authenticationToken == null) {
            chain.doFilter(request,response);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader(SecruityConstant.SECRUITY_TOKEN);
        if (!StringUtils.isEmpty(token) && token.startsWith(SecruityConstant.SECRUITY_TOKEN_PRE)) {
            try {
                Jws<Claims> parseToken = Jwts.parserBuilder()
                        .setSigningKey(SecruityConstant.SECRUITY_STRKEY.getBytes())
                        .build()
                        .parseClaimsJws(token.replace(SecruityConstant.SECRUITY_TOKEN_PRE,""));
                String username = parseToken.getBody().getSubject();

                List<GrantedAuthority> authorities = ((List<String>)parseToken.getBody().get("role"))
                        .stream().map(authorite -> new SimpleGrantedAuthority(authorite)).collect(Collectors.toList());
                if (!StringUtils.isEmpty(username)) {
                    return new UsernamePasswordAuthenticationToken(username,null,authorities);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
